package com.dyz.leetcode._13_binaryTree;

import com.dyz.leetcode.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

public class _114_flatten {
    public void flatten(TreeNode root) {
        List<TreeNode> list = new ArrayList<>();
        preOrder(root, list);
        for(int i=1; i<list.size(); i++){
            TreeNode prev = list.get(i-1);
            TreeNode curr = list.get(i);
            prev.left = null;
            prev.right = curr;
        }
    }

    private void preOrder(TreeNode root, List<TreeNode> list){
        if(root==null){return;}
        list.add(root);
        preOrder(root.left, list);
        preOrder(root.right, list);
    }

    //前序遍历
    public void flatten1(TreeNode root) {
        if(root==null){return;}
        ArrayDeque<TreeNode> stack = new ArrayDeque<>();
        stack.push(root);
        TreeNode prev = null;
        while (!stack.isEmpty()){
            TreeNode curr = stack.pop();
            if(prev!=null){
                prev.left = null;
                prev.right = curr;
            }
            TreeNode left = curr.left;
            TreeNode right = curr.right;

            if(right!=null){stack.push(right);}
            if(left!=null){stack.push(left);}
            prev = curr;
        }
    }

    public void flatten2(TreeNode root) {
        if (root == null) {return;}
        TreeNode curr = root;
        while (curr != null) {
            if (curr.left != null) {
                TreeNode left = curr.left;
                TreeNode pre = left;
                while (pre.right != null) {
                    pre = pre.right;
                }
                pre.right = curr.right;
                curr.left = null;
                curr.right = left;
            }
            curr = curr.right;
        }
    }
}
